import React, { useRef, useState } from 'react';
import styles from './index.module.less';
import Tabs from '@/components/tabs';
import ApproveCard from '@/components/card';
import { DocList } from '@/services/official-doc';
import AntdRefreshList from '@/components/antd-refresh-list';
import { PrintNum } from '@/utils';
import { useRefreshList } from '@/hooks/use-refresh-list';
import EmptyRefresh from '@/components/empty/empty-refresh';
import EmptyLoading from '@/components/empty/empty-loading';
import { applyType } from '@/constants';
import { Prompt } from 'react-router-dom';
import history from '@/utils/history';
import { APPROVAL_STATUS } from '@/pages/declare/constants';
import { CacheRouteParams, GetRouteCache } from '@/utils/route-utils';

// 视窗高度减去减去头部和底部组件的高度
const height = document.documentElement.clientHeight - document.documentElement.clientWidth * (40 + 50 + 5) / 375;
const defaultPageSize = 10;

export enum DOC_TYPE {
  MY_PUBLISH = 1, // 我的发文
  MY_RECEIVE = 2 // 我的收文
}

const Log: React.FC<any> = (props) => {
  const menu = useRef([
    { text: '我的发文', value: DOC_TYPE.MY_PUBLISH },
    { text: '我的收文', value: DOC_TYPE.MY_RECEIVE }
  ]);

  const [pageSize, setPageSize] = useState(defaultPageSize);

  const {
    showDom,
    refreshing,
    loadingMore,
    dataSource,
    searchData,
    setDatasource,
    handleRefresh,
    handleLoadMore,
    handleSearch,
    routeWillLeave
  } = useRefreshList({
    routeProps: props,
    initSearchData: { type: DOC_TYPE.MY_PUBLISH }, // 我的发文 1 我的收文 2
    cacheRouteList: [
      '/official-doc/detail',
      '/declare/detail'
    ],
    pullData: async (options) => {
      const { params, setLastId, setSurplusTotal, setData } = options;
      const reqParams = {
        lastId: params.lastId,
        pageSize: params?.pageNum ? PrintNum(params?.pageNum * defaultPageSize) : defaultPageSize,
        searchType: params?.type
      };
      const res = await DocList(reqParams);
      const list = formatData(res.data?.rows) || [];
      const surplusTotal = res.data?.total - list.length; // 加载完当前请求的数据还剩多少条数据
      setSurplusTotal(surplusTotal < 0 ? 0 : surplusTotal);
      setPageSize(params?.pageNum ? PrintNum(params?.pageNum * defaultPageSize) : defaultPageSize);
      setData(params?.lastId ? dataSource.concat(list) : list);
      setLastId(list[list.length - 1]?.id);
    }
  });

  const formatData = (data: any[]): any => {
    data?.forEach((item) => {
      item.formData = [
        { label: '公文号', value: item.documentCode || '无' },
        { label: '会议日期', value: item.meetingDate?.slice(0, 10) || '无' },
        { label: '主持人', value: item.anchorName || '无' }
      ];
      item.cardTitle = item.documentTitle;
    });
    return data;
  };

  const handleJump2Detail = (item: any) => {
    if (item.documentEnterType === 1 && item.status === APPROVAL_STATUS.Pass) { // documentEnterType: 1-线上公文，2-线下公文;
      return history.push({
        pathname: `/official-doc/detail/${item.id}`,
        query: {
          enterType: searchData?.type,
          procRecordId: item.procRecordId,
          applyType: applyType.ONLINE_DOCUMENT_APPLY
        }
      });
    }
    if (item.documentEnterType === 2) {
      return history.push({
        pathname: `/official-doc/detail/${item.id}`,
        query: {
          enterType: searchData?.type
        }
      });
    }
    history.push({
      pathname: '/declare/detail',
      query: {
        applyType: applyType.ONLINE_DOCUMENT_APPLY,
        innerProcDefId: item.innerProcDefId,
        procRecordId: item.procRecordId,
        applyId: item.id,
        // resubmit: item.status !== APPROVAL_STATUS.Draft ? true : false,
        title: item.documentTitle,
        status: item.status,
        enterType: searchData?.type
      }
    });
  };

  return (
    <div className={styles.wrap}>
      <Tabs data={menu.current} dataType={searchData?.type} onChange={(val) => handleSearch({ type: val })} />
      {
        showDom ?
          <div className={styles.cardList}>
            {
              dataSource?.length > 0 ?
                <AntdRefreshList
                  height={height}
                  initialListSize={pageSize}
                  dataSource={dataSource}
                  refreshing={refreshing}
                  loadingMore={loadingMore}
                  renderRow={(item, sectionID, index) => (
                    <div className={styles.cardItem} key={index}>
                      <a onClick={() => handleJump2Detail(item)}>
                        <ApproveCard data={item} hasAvatar withStatus></ApproveCard>
                      </a>
                    </div>
                  )}
                  onRefresh={handleRefresh}
                  onEndReached={handleLoadMore}
                />
                : (
                  <EmptyRefresh
                    refreshing={refreshing}
                    onRefresh={handleRefresh}
                  />
                )
            }
          </div>
          : <EmptyLoading />
      }
      <Prompt message={routeWillLeave} />
    </div>
  );
};

export default Log;